package com.rerun.phone.memberuser;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rerun.common.anno.ResponseExceptionReturn;
import com.rerun.common.bean.Rest;
import com.rerun.common.controller.SuperController;
import com.rerun.common.util.Validator;
import com.rerun.entity.MemberUser;
import com.rerun.entity.vo.MemberUserFlagVo;
import com.rerun.entity.vo.UserInfoVo;
import com.rerun.enums.MemberStatusEnum;
import com.rerun.enums.RedisKeySuffixEnum;
import com.rerun.service.IMemberUserService;
import com.rerun.service.ISmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 用户接口
 *
 * @author Administrator
 */
@RestController()
@Api(value = "求职端-账号相关", description = "求职端-账号相关")
@RequestMapping("/memberApi/memberUser")
public class MemberUserController extends SuperController {

    /**
     * The constant logger.
     */
    public static final Logger logger = LoggerFactory.getLogger(MemberUserController.class);
    @Autowired
    private IMemberUserService memberUserService;
    @Autowired
    private ISmsService iSmsService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * The Map.
     */
    Map<String, String> map = null;
    /**
     * The Code.
     */
    String code = null;
    /**
     * The Msg.
     */
    String msg = null;

    /**
     * Member user register rest.
     *
     * @param phone    the phone
     * @param password the password
     * @param smsCode  the sms code
     * @param sex      the sex
     * @return the rest
     */
//注册
    @ApiOperation(value = "注册", notes = "通过手机号短信注册", httpMethod = "POST")
    @RequestMapping("/register")
    @ResponseExceptionReturn
    public Rest MemberUserRegister(@RequestParam String phone, @RequestParam String password, @RequestParam String smsCode, @RequestParam long sex) {
        if (!iSmsService.verifySmsCode(phone, smsCode)) {
            return Rest.failure("验证码不匹配");
        }
        //根据手机号查询
        EntityWrapper<MemberUser> wrapper = new EntityWrapper<MemberUser>();
        wrapper.where("phone={0}", phone);
        //校验是否为手机号
        if (!Validator.isMobile(phone)) {
            return Rest.failure("请输入正确的手机号");
        }
        //去重
        MemberUser user = memberUserService.selectOne(wrapper);
        if (user != null) {//已注册
            return Rest.failure("用户信息已注册");
        } else {
            MemberUser memberuser = new MemberUser();
            // MD5,"密码","盐",加密次数
            String pwd = new SimpleHash("MD5", password, phone, 1024).toString();
            memberuser.setSex(sex);
            memberuser.setPhone(phone);
            memberuser.setPassword(pwd);
            memberuser.setCreateTime(new Date());
            //1 未激活   2 激活 3冻结
            memberuser.setStatus(MemberStatusEnum.ACTIVATE.getType());
            boolean result = memberUserService.insert(memberuser);

            if (result == true) {
                return Rest.ok("ok");
            }
        }
        return Rest.failure("注册失败");
    }

    /**
     * Member user login rest.
     *
     * @param phone    the phone
     * @param password the password
     * @return the rest
     */
//登录
    @ApiOperation(value = "登录", notes = "通过手机号登录", httpMethod = "GET")
    @RequestMapping("/memberUserLogin")
    @ResponseExceptionReturn
    public Rest MemberUserLogin(@RequestParam String phone, @RequestParam String password) {
        try {
            //校验是否为手机号
            if (!Validator.isMobile(phone)) {
                return Rest.failure("手机号或密码错误");
            }
            // MD5,"密码","盐",加密次数
            String pwd = new SimpleHash("MD5", password, phone, 1024).toString();
            EntityWrapper<MemberUser> wrapper = new EntityWrapper<>();
            wrapper.where("phone={0}", phone);
            MemberUser user = memberUserService.selectOne(wrapper);
            //判断是否为激活状态
            if ((MemberStatusEnum.ACTIVATE.getType()).equals(user.getStatus())) {
                //判断是否正确
                if (user.getPassword().equals(pwd)) {

                    //上次登录时间
                    user.setLastLoginTime(user.getLoginTime());
                    //当前登录时间
                    user.setLoginTime(new Date());
                    //上次登录IP
                    user.setLastLoginIp(user.getLoginIp());
                    //本次登录ip
//                    user.setLoginIp(HttpUtil.getIpAddress(request));

                    //加缓存
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    valueOperations.set(user.getId() + RedisKeySuffixEnum.APP_MEMBER_CACHE_KEY_SUFFIX.getKey(), user);
                    //清除密码
                    user.setPassword(null);
                    return Rest.okData(user);
                } else {

                    return Rest.failure("密码错误");
                }

            } else {
                return Rest.ok("手机号未激活");

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("登录失败具体原因" + e.getMessage());
        }

        return Rest.failure("手机号或密码错误");
    }

    /**
     * Update member password rest.
     *
     * @param user    the user
     * @param smsCode the sms code
     * @return the rest
     */
    @ApiOperation(value = "修改 激活", notes = "MS01 未激活   MS02激活", httpMethod = "POST")
    @RequestMapping("/updatePassword")
    @ResponseExceptionReturn
    public Rest UpdateMemberPassword(MemberUserFlagVo user, String smsCode) {

        String phone = user.getPhone();
        /*if (!iSmsService.verifySmsCode(phone, smsCode)) {
            return Rest.failure("验证码不匹配");
        }*/
        EntityWrapper<MemberUser> wrapper = new EntityWrapper<>();
        wrapper.where("phone={0}", phone);
        MemberUser meberUser = memberUserService.selectOne(wrapper);

        if (Objects.isNull(meberUser)) {
            return Rest.failure("查无此人");
        }

        String status = meberUser.getStatus();

        if (MemberStatusEnum.FREEZE.getType().equals(status)) {
            return Rest.failure("账户冻结");
        }

        //输入的旧密码
        String oldPass = user.getPassword();
        if (oldPass == null) {
            return Rest.failure("请输入旧密码");
        }
        String oldCipher = new SimpleHash("MD5", oldPass, phone, 1024).toString();
        //数据库获取的旧密码
        String oldSource = meberUser.getPassword();
        // MS01 未激活   MS02激活
        //如果用户状态为未激活状态   改为激活状态
        if (MemberStatusEnum.INACTIVE.getType().equals(status)) {

            meberUser.setStatus(MemberStatusEnum.ACTIVATE.getType());
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(meberUser.getId() + RedisKeySuffixEnum.APP_MEMBER_CACHE_KEY_SUFFIX.getKey(), meberUser);
        }

        if (oldCipher.equals(oldSource)) {
            String newPass = user.getNewpassword();
            String newCipher = new SimpleHash("MD5", newPass, phone, 1024).toString();
            meberUser.setPassword(newCipher);
            memberUserService.updateById(meberUser);
            return Rest.ok("操作成功");
        }

        return Rest.failure("请输入新密码");
    }

    /**
     * Get member password rest.
     *
     * @param phone    the phone
     * @param password the password
     * @param smsCode  the sms code
     * @return the rest
     */
    @ApiOperation(value = "找回密码", httpMethod = "POST")
    @RequestMapping("/getPassword")
    @ResponseExceptionReturn
    public Rest GetMemberPassword(@RequestParam String phone, @RequestParam String password, @RequestParam String smsCode) {
        //校验是否为手机号
        if (!Validator.isMobile(phone)) {
            return Rest.failure("请输入正确的手机号");
        }
        //校验是否注册
        EntityWrapper<MemberUser> wrapper = new EntityWrapper<MemberUser>();
        wrapper.where("phone={0}", phone);
        MemberUser meberUser = memberUserService.selectOne(wrapper);

        if (Objects.isNull(meberUser)) {
            return Rest.failure("查无此人");
        }
        if ((MemberStatusEnum.INACTIVE.getType()).equals(meberUser.getStatus())) {
            return Rest.ok("手机号未激活");
        }
        //发送验证码 校验
        if (!iSmsService.verifySmsCode(phone, smsCode)) {
            return Rest.failure("验证码不匹配");
        }
        // MD5,"密码","盐",加密次数
        String pwd = new SimpleHash("MD5", password, phone, 1024).toString();
        meberUser.setPassword(pwd);
        boolean result = memberUserService.update(meberUser, wrapper);
        if (result) {
            return Rest.ok("密码设置成功");
        }
        return Rest.failure("密码设置失败");
    }


    /**
     * Login out rest.
     *
     * @param id the id
     * @return the rest
     */
//退出登录
    @ApiOperation(value = "退出登录", notes = "退出登录", httpMethod = "GET")
    @RequestMapping("/loginOut/{id}")
    @ResponseExceptionReturn
    public Rest LoginOut(@PathVariable(value = "id") String id) {
        redisTemplate.delete(id + RedisKeySuffixEnum.APP_MEMBER_CACHE_KEY_SUFFIX.getKey());
        return Rest.ok("退出成功");

    }

    /**
     * 通过用户id获取 个人信息
     *
     * @param memberId the member id
     * @return rest rest
     */
    @ApiOperation(value = "个人信息", notes = "根据用户id获取其个人信息", httpMethod = "GET")
    @RequestMapping(value = "/getMemberMessage/{memberId}", method = RequestMethod.GET)
    @ResponseExceptionReturn
    public Rest selectMemberMessage(@ApiParam(required = true, name = "memberId", value = "用户id") @PathVariable("memberId") String memberId) {
        return Rest.okData(memberUserService.getUserInfo(memberId));
    }

    /**
     * 编辑用户个人信息 (完善信息)
     *
     * @param vo the vo
     * @return the rest
     */
    @ApiOperation(value = "编辑信息", notes = "根据用户id获取编辑个人信息", httpMethod = "POST")
    @RequestMapping(value = "/updateMemberMessage", method = RequestMethod.POST)
    @ResponseExceptionReturn
    public Rest updateUserInfo(@ModelAttribute UserInfoVo vo) {
        memberUserService.updateUserInfo(vo);
        return Rest.ok("编辑成功");
    }


}
